// Provide an abstract class as Todo database

package org.fuckerfucker.todoapp_kotlin.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import org.fuckerfucker.todoapp_kotlin.data.model.Priority
import org.fuckerfucker.todoapp_kotlin.data.model.Todo

// TODO: I do need exportSchema
@Database(entities = [Todo::class], version=1, exportSchema = true)
@TypeConverters(Converter::class)
abstract class TodoDB : RoomDatabase(){
    abstract fun todoDao(): TodoDao

    // static block
    companion object {
        @Volatile
        private var INSTANCE: TodoDB? = null

        fun getDB(context: Context): TodoDB =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(
                context.applicationContext,
                TodoDB::class.java, "todo_database"
            ).build()
    }

}

// helper class for converting priority to string
internal  class Converter {
    @TypeConverter
    fun fromPriority(priority: Priority): String = priority.name

    @TypeConverter
    fun toPriority(priority: String): Priority = Priority.valueOf(priority)
}